﻿using System.Collections.Generic;
using System.Linq;
using LinFu.IoC.Factories;
using LinFu.IoC.Interfaces;

namespace LinFu.Ioc.MoqIntegration
{
    /// <summary>
    /// Inspects the requested service type and returns a mocked service instance if 
    /// mocking has been enabled for the service type.     
    /// </summary>
    /// <seealso cref="ContainerExtensions"/>
    public class MockPreprocessor : IPreProcessor
    {
        private readonly IList<MockServiceInfo> _mockedServices;

        /// <summary>
        /// Initializes a new instance of the <see cref="MockPreprocessor"/>
        /// </summary>
        /// <param name="mockedServices"></param>
        public MockPreprocessor(IList<MockServiceInfo> mockedServices)
        {
            _mockedServices = mockedServices;
        }

        /// <summary>
        /// Inspects the service request and return a mocked service if available.
        /// </summary>        
        public void Preprocess(IServiceRequest request)
        {
            var serviceName = string.IsNullOrEmpty(request.ServiceName) ? null : request.ServiceName;

            var mockedServiceInfo =
                _mockedServices.Where(
                    ms => ms.ServiceType == request.ServiceType && ms.ServiceName == serviceName).FirstOrDefault
                    ();

            if (mockedServiceInfo != null)
                request.ActualFactory = new FunctorFactory(r => mockedServiceInfo.Mock.Object);
        }
    }

}
